from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from appapi.serializers import UserSerializer, GroupSerializer,DogSerializer
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from appapi.models import *
import logging
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user
logger = logging.getLogger(__name__)
page_num = 9

'''
class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
'''
@login_required
def dog_list(request):
    user = get_user(request)
    logger.error("打印用户")
    logger.error(user.id)
    """
    List all code Dogs, or create a new Dog.
    """

    if request.method == 'GET':
        page = 1
        type = 1
        maintype = 1
        searchid = None
        try:
            searchid = int(request.GET.get("searchid", 1))
            print('searchid----->', searchid)
            if searchid < 0:
                searchid = None
        except ValueError:
            searchid = None
        try:
            maintype = int(request.GET.get("maintype", 1))
            print('maintype----->', maintype)
            if maintype < 1:
                maintype = 1
        except ValueError:
            maintype = 1
        try:
            page = int(request.GET.get("page", 1))
            print('page----->', page)
            if page < 1:
                page = 1
        except ValueError:
            page = 1
        try:
            type = int(request.GET.get("type", 1))
            print('type----->', type)
            if type < 1:
                type = 1
        except ValueError:
            type = 1
        begin_num = (page-1)*page_num
        end_num = page*page_num
        Dogs = []
        if maintype == 1 and type == 1:#首页全部
            #obj = userdog.objects.get(user__id=user.id)
            userdog1 = userdog.objects.filter(user__id=user.id).values_list('dog')[begin_num:end_num]
            print('userdog1----->')
            print(userdog1)
            ids = ""
            for rack in userdog1:
                print(rack[0])
                ids += str(rack[0]) + ","
            ids = ids[0:-1]
            if ids == None or ids == '':
                ids = '0'
            Dogs = Dog.objects.extra(where=['id IN (' + ids + ')'])

        if maintype == 1 and type != 1:  # 首页集市
            # obj = userdog.objects.get(user__id=user.id)
            userdog1 = fairinfo.objects.filter(owner__id=user.id,type=type).values_list('dog')[begin_num:end_num]
            print('userdog1----->')
            print(userdog1)
            ids = ""
            for rack in userdog1:
                print(rack[0])
                ids += str(rack[0]) + ","
            ids = ids[0:-1]
            if ids == None or ids == '':
                ids = '0'
            Dogs = Dog.objects.extra(where=['id IN (' + ids + ')'])

        if maintype == 2:  # 广场集市
            # obj = userdog.objects.get(user__id=user.id)
            userdog1 = []
            logger.error("打印searchid:")
            logger.error(searchid)
            if searchid == None:
                userdog1 = fairinfo.objects.filter(type=type).values_list('dog')[begin_num:end_num]
            else:
                userdog1 = fairinfo.objects.filter(type=type,dog__id=searchid).values_list('dog')[begin_num:end_num]
            print('userdog1----->')
            print(userdog1)
            ids = ""
            for rack in userdog1:
                print(rack[0])
                ids += str(rack[0]) + ","
            ids = ids[0:-1]
            if ids == None or ids == '':
                ids = '0'
            Dogs = Dog.objects.extra(where=['id IN (' + ids + ')'])


        #Dogs = Dog.objects.order_by('id').all()[begin_num:end_num]
        serializer = DogSerializer(Dogs, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = DogSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

@csrf_exempt
@login_required
def dog_detail(request, pk):
    """
    Retrieve, update or delete a code Dog.
    """
    maintype = 1
    try:
        maintype = int(request.GET.get("maintype", 1))
        print('maintype----->', maintype)
        if maintype < 0:
            maintype = 1
    except ValueError:
        maintype = 1
    try:
        dog = Dog.objects.get(pk=pk)
        #狗主人和登录用户判断
        #狗交易类型
    except dog.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = DogSerializer(dog)
        return JsonResponse(serializer.data)
'''
    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = DogSerializer(dog, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        Dog.delete()
        return HttpResponse(status=204)
'''